# -*- coding: utf-8 -*-
"""
pydantic
校验

"""
from fastapi import APIRouter, Body, BackgroundTasks, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

from datetime import date, timedelta

import importlib
import logging

logger = logging.getLogger(__name__)

task_router = APIRouter(prefix='/task')


class PostRequest(BaseModel):
    reference: str = Field(...)  #
    # # 注意要使用default_factory，而不是default，否则不会动态生成，值是固定的
    # start_date: date = Field(default_factory=date.today)
    # end_date: date = Field(default_factory=date.today)
    kwargs: dict = Field({})

    pass


@task_router.post('/add')
def add_task(post_request: PostRequest, background_tasks: BackgroundTasks, query_param: str = None):
    # kwargs = {
    #     "start_date": post_request.start_date,
    #     "end_date": post_request.end_date,
    # }
    kwargs = post_request.kwargs
    module, symbol = post_request.reference.rsplit(sep='.', maxsplit=1)
    instance = importlib.import_module(module)
    function = getattr(instance, symbol)
    logger.info(f'before task len:{len(background_tasks.tasks)}')
    background_tasks.add_task(function, **kwargs)
    logger.info(f'after task len:{len(background_tasks.tasks)}')
    return JSONResponse(content={'message': 'success'}, status_code=status.HTTP_200_OK)


if __name__ == '__main__':
    pass
